package com.ruoyi.system.controller;

import java.util.List;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import cn.hutool.crypto.symmetric.SymmetricCrypto;
import cn.hutool.json.JSONUtil;
import com.ruoyi.system.domain.vo.HolderVo;
import com.ruoyi.system.domain.vo.QrCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.annotation.RequiresPermissions;
import com.ruoyi.system.domain.BizHousehold;
import com.ruoyi.system.service.IBizHouseholdService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;

/**
 * 住户Controller
 *
 * @author ruoyi
 * @date 2023-01-25
 */
@RestController
@RequestMapping("/household")
public class BizHouseholdController extends BaseController
{
    @Autowired
    private IBizHouseholdService bizHouseholdService;

    //TODO 此处应该将key写入配置文件
    private final String key = "hW7vfIE6qmNMTyh0lZh2mw==";

    /**
     * 查询住户列表
     */
    @RequiresPermissions("system:household:list")
    @GetMapping("/list")
    public TableDataInfo list(BizHousehold bizHousehold)
    {
        startPage();
        List<BizHousehold> list = bizHouseholdService.selectBizHouseholdList(bizHousehold);
        //TODO 入日志库报错
        String json = JSONUtil.toJsonStr(list);
        System.out.println(json);
        return getDataTable(list);
    }

    /**
     * 导出住户列表
     */
    @RequiresPermissions("system:household:export")
    @Log(title = "住户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BizHousehold bizHousehold)
    {
        List<BizHousehold> list = bizHouseholdService.selectBizHouseholdList(bizHousehold);
        ExcelUtil<BizHousehold> util = new ExcelUtil<BizHousehold>(BizHousehold.class);
        util.exportExcel(response, list, "住户数据");
    }

    /**
     * 获取住户详细信息
     */
    @RequiresPermissions("system:household:query")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id)
    {
        return success(bizHouseholdService.selectBizHouseholdById(id));
    }

    /**
     * 新增住户
     */
    @RequiresPermissions("system:household:add")
    @Log(title = "住户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizHousehold bizHousehold)
    {
        return toAjax(bizHouseholdService.insertBizHousehold(bizHousehold));
    }

    /**
     * 修改住户
     */
    @RequiresPermissions("system:household:edit")
    @Log(title = "住户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizHousehold bizHousehold)
    {
        return toAjax(bizHouseholdService.updateBizHousehold(bizHousehold));
    }

    /**
     * 删除住户
     */
    @RequiresPermissions("system:household:remove")
    @Log(title = "住户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids)
    {
        return toAjax(bizHouseholdService.deleteBizHouseholdByIds(ids));
    }

    /**
     * 加密住户id和核酸任务id
     * 传userId,去后台根据userId查taskId
     */
    @GetMapping("/encodeUrl/{userId}")
    public AjaxResult encodeUrl(@PathVariable String userId){
        /*
        思路:
        1.获取密钥(base64字符串).解析为byte[]
        2.传userId,去后台根据userId查taskId
        3.userId和taskId分别加密,生成的密文为byte[],转换为base64格式或者hex格式
        4.返回
         */
        //1.取密钥
        byte[] keyBytes = Base64.decode(key);
        //2.因为核酸任务模块尚未完成,此处随机生成雪花Id或UUID作为taskId
        //TODO 去后台根据userId查taskId
        String taskId = IdUtil.getSnowflakeNextIdStr();
        //3.分别加密
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, keyBytes);
        //通过此方法加密直接获取到的是Base64字符串,无需再次编码解码
        String encodeUserId = aes.encryptBase64(userId);
        String encodeTaskId = aes.encryptBase64(taskId);
        //4.返回结果
        QrCodeVo vo = new QrCodeVo();
        vo.setUserId(encodeUserId);
        vo.setTaskId(encodeTaskId);
        return  AjaxResult.success(vo);
    }

    /**
     * 解密住户id和核酸任务id,并且返回用户实体信息和核酸任务实体信息
     * 传userId和taskId
     */
    @GetMapping("/decodeUrl")
    public AjaxResult decodeUrl(QrCodeVo qrCodeVo){
        /*
        思路:
        1.获取密钥(base64字符串).解析为byte[]
        2.userId和taskId分别解密
        3.去住户表和核酸任务表中查出实体信息
        4.返回
         */
        //1.取密钥
        byte[] keyBytes = Base64.decode(key);
        //2.分别解密
        SymmetricCrypto aes = new SymmetricCrypto(SymmetricAlgorithm.AES, keyBytes);
        //通过此方法解密直接获取到的是Base64字符串,无需再次编码解码
        String userId = aes.decryptStr(qrCodeVo.getUserId());
        String taskId = aes.decryptStr(qrCodeVo.getTaskId());
        //3.根据解密后的id查询实体
        BizHousehold bizHousehold = bizHouseholdService.selectBizHouseholdById(userId);
        //TODO 根据taskId查询核酸任务相关数据
        //4.返回结果
        HolderVo holderVo = new HolderVo();
        holderVo.setUserId(userId);
        holderVo.setTaskId(taskId);
        holderVo.setBizHousehold(bizHousehold);
        return  AjaxResult.success(holderVo);
    }


}
